//
//  VRSafetyTestingViewController.m
//  VRFirefighting
//
//  Created by Veer on 2018/8/23.
//  Copyright © 2018年 Veer. All rights reserved.
//

#import "VRSafetyTestingViewController.h"
#import "VRSafetyTestingDetailViewController.h"

#import "VRSafetyTestingListCell.h"

#import "UIImage+VR.h"
#import "VRSafetyTestingModel.h"

@interface VRSafetyTestingViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *leftBtn;
@property (nonatomic, strong) UIButton *rightBtn;

@property (nonatomic, strong) NSMutableArray<VRSafetyTestingModel *> *safetyTestingModelArray;
@property (nonatomic, strong) NSMutableArray<VRSafetyTestingModel *> *modelArray0;
@property (nonatomic, strong) NSMutableArray<VRSafetyTestingModel *> *modelArray1;
@property (nonatomic, assign) NSInteger currentPage;

@property (nonatomic, assign) NSInteger currentSelectType;

@end

@implementation VRSafetyTestingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = ScrollViewBgColor;
    self.title = @"安全排查记录";
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.safetyTestingModelArray = [NSMutableArray array];
    self.modelArray0 = [NSMutableArray array];
    self.modelArray1 = [NSMutableArray array];
    
    [self setupSubView];
    weakify(self)
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        strongify(self)
        [self getSafeKnowlegeWithIsRemoveArray:YES];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        strongify(self)
        [self getSafeKnowlegeWithIsRemoveArray:NO];
    }];
    
    [((MJRefreshAutoNormalFooter *)self.tableView.mj_footer) setTitle:@"没有更多了" forState:MJRefreshStateNoMoreData];
    
    [self getSafeKnowlegeWithIsRemoveArray:YES];
}

- (void)setupSubView
{
    self.tableView.y = NAVIGATION_BAR_HEIGHT + 40;
    
    UIButton *leftBtn = [XButton buttonWithType:UIButtonTypeCustom];
//    leftBtn.adjustsImageWhenHighlighted = NO;
    leftBtn.enabled = NO;
    leftBtn.tag = 0;
    [leftBtn setTitle:@"已巡查" forState:UIControlStateNormal];
    leftBtn.titleLabel.font = VRFont(16);
    [leftBtn setTitleColor:RGB(78, 172, 57) forState:UIControlStateNormal];
    [leftBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
    [leftBtn setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    [leftBtn setBackgroundImage:[UIImage imageWithColor:RGB(78, 172, 57)] forState:UIControlStateDisabled];
    [leftBtn addTarget:self action:@selector(onSegmentBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftBtn];
    self.leftBtn = leftBtn;
    [leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.view.mas_centerX);
        make.top.mas_equalTo(NAVIGATION_BAR_HEIGHT);
        make.left.mas_equalTo(0);
        make.height.mas_equalTo(40);
    }];
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    rightBtn.adjustsImageWhenHighlighted = NO;
    rightBtn.tag = 1;
    [rightBtn setTitle:@"未巡查" forState:UIControlStateNormal];
    rightBtn.titleLabel.font = VRFont(16);
    [rightBtn setTitleColor:RGB(225, 11, 24) forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
    [rightBtn setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    [rightBtn setBackgroundImage:[UIImage imageWithColor:RGB(225, 11, 24)] forState:UIControlStateDisabled];
    [rightBtn addTarget:self action:@selector(onSegmentBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:rightBtn];
    self.rightBtn = rightBtn;
    [rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(NAVIGATION_BAR_HEIGHT);
        make.left.mas_equalTo(self.view.mas_centerX);
        make.height.mas_equalTo(40);
    }];
}

#pragma mark - networking
- (void)getSafeKnowlegeWithIsRemoveArray:(BOOL)isRemoveArray
{
    
    if (isRemoveArray) {
        self.currentPage = 1;
    }
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"UserID"] = [VRUser shareUser].token;
    param[@"page"] = @(self.currentPage++);
    
    if (isRemoveArray) {
        [self.modelArray0 removeAllObjects];
        [self.modelArray1 removeAllObjects];
    }
    
    weakify(self)
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [JKNetworking postWithSign:GetAllSafetyTesting parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            NSArray *modelArray = [VRSafetyTestingModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            if (isRemoveArray) {
                self.safetyTestingModelArray = [NSMutableArray arrayWithArray:[modelArray copy]];
            }else{
                [self.safetyTestingModelArray addObjectsFromArray:[modelArray copy]];
            }
            
            // 处理数据
            for (VRSafetyTestingModel *model in modelArray) {
                if ([model.fState isEqualToString:@"error"]) {
                    [self.modelArray1 addObject:model];
                }else{
                    [self.modelArray0 addObject:model];
                }
            }
            
            if (modelArray.count < 20) {
                
                [self.tableView.mj_footer setState:MJRefreshStateNoMoreData];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //                [self.tableView beginUpdates];
                //                [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationNone];
                [self.tableView.mj_header endRefreshing];
                [self.tableView reloadData];
                [hud hideAnimated:YES];
            });
        }else if(msg.length > 0){
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView.mj_header endRefreshing];
                [SVProgressHUD showErrorWithStatus:msg];
                [hud hideAnimated:YES];
            });
        }
    } error:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
            [hud hideAnimated:YES];
            [self.tableView.mj_header endRefreshing];
        });
    }];
}

#pragma mark - action
- (void)onSegmentBtnClick:(UIButton *)sender
{
    
    self.currentSelectType = sender.tag;
    self.leftBtn.enabled = !self.leftBtn.enabled;
    self.rightBtn.enabled = !self.rightBtn.enabled;
    [self.tableView reloadData];
}

#pragma mark - delegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.currentSelectType == 0) {
        return self.modelArray0.count;
    }
    return self.modelArray1.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 140 + 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    VRSafetyTestingListCell *cell = [VRSafetyTestingListCell cellWith:tableView];
    if (self.currentSelectType == 0) {
        cell.model = self.modelArray0[indexPath.row];
    }else{
        cell.model = self.modelArray1[indexPath.row];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    VRSafetyTestingDetailViewController *detailVc = [[VRSafetyTestingDetailViewController alloc] init];
    if (self.currentSelectType == 0) {
        detailVc.fID = self.modelArray0[indexPath.row].fID;
    }else{
        detailVc.fID = self.modelArray1[indexPath.row].fID;
    }
    
    [self.navigationController pushViewController:detailVc animated:YES];
}


#pragma mark - lazy
- (UITableView *)tableView
{
    if (_tableView == nil) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, kScreenWidth, kScreenHeight - NAVIGATION_BAR_HEIGHT - 40) style:UITableViewStylePlain];
        _tableView.backgroundColor = ScrollViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableHeaderView = [[UIView alloc] init];
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        
        UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0)];
        _tableView.tableFooterView = view1;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.sectionFooterHeight = 0.01;
        [self.view addSubview:self.tableView];
        //        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        //            make.left.right.bottom.mas_equalTo(self.view);
        //            make.top.mas_equalTo(0);
        //        }];
    }
    return _tableView;
}


@end
